import { ref, onMounted, onUnmounted } from 'vue'
import SockJS from 'sockjs-client'
import webstomp from 'webstomp-client'

export function useWebSocket() {
  const client = ref<any>(null)
  const connected = ref(false)

  const connect = () => {
    console.log('正在连接WebSocket...')
    // 获取API根路径，确保WebSocket连接到正确的服务器
    const baseURL = import.meta.env.VITE_API_BASE_URL || 'http://localhost:8080'
    const wsUrl = `${baseURL}/ws`
    console.log('WebSocket URL:', wsUrl)
    
    const socket = new SockJS(wsUrl)
    client.value = webstomp.over(socket)

    // 设置调试模式
    client.value.debug = true

    client.value.connect(
      {},
      () => {
        connected.value = true
        console.log('WebSocket连接成功!')
      },
      (error: any) => {
        console.error('WebSocket连接错误:', error)
        connected.value = false
        // 尝试重新连接
        setTimeout(() => {
          console.log('尝试重新连接WebSocket...')
          connect()
        }, 3000)
      }
    )
  }

  const disconnect = () => {
    if (client.value && connected.value) {
      client.value.disconnect()
      connected.value = false
      console.log('WebSocket已断开连接')
    }
  }

  const subscribe = (destination: string, callback: (message: any) => void) => {
    if (!client.value || !connected.value) {
      console.error('WebSocket未连接，无法订阅')
      return null
    }

    console.log(`正在订阅: ${destination}`)
    return client.value.subscribe(destination, (message: any) => {
      const body = JSON.parse(message.body)
      callback(body)
    })
  }

  const sendMessage = (destination: string, message: any) => {
    if (!client.value || !connected.value) {
      console.error('WebSocket未连接，无法发送消息')
      return
    }

    console.log(`发送消息到: ${destination}`, message)
    client.value.send(destination, JSON.stringify(message))
  }

  onMounted(() => {
    console.log('组件挂载，连接WebSocket')
    connect()
  })

  onUnmounted(() => {
    console.log('组件卸载，断开WebSocket')
    disconnect()
  })

  return {
    client,
    connected,
    connect,
    disconnect,
    subscribe,
    sendMessage
  }
} 